package com.shanling.shanlingcontroller.persenter;

import android.util.Log;

import com.shanling.shanlingcontroller.BuildConfig;
import com.shanling.shanlingcontroller.CustomApplication;
import com.shanling.shanlingcontroller.R;
import com.shanling.shanlingcontroller.bean.ApptokenBean;
import com.shanling.shanlingcontroller.bean.ResultException;
import com.shanling.shanlingcontroller.bean.VerificationcodeBean;
import com.shanling.shanlingcontroller.http.BaseResult;
import com.shanling.shanlingcontroller.http.BuildFactory;
import com.shanling.shanlingcontroller.http.DeviceApi;
import com.shanling.shanlingcontroller.http.HttpConstants;
import com.shanling.shanlingcontroller.persenter.contract.Registcontract;
import com.shanling.shanlingcontroller.utils.CodeMessgeUtils;
import com.shanling.shanlingcontroller.utils.Md5Util;
import com.shanling.shanlingcontroller.utils.PhoneUtils;
import com.shanling.shanlingcontroller.utils.PreferenceUtil;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by ch1 on 2019/9/29.
 */

public class RegistPersenter extends RxPresenter<Registcontract.View> implements Registcontract.Presenter {
    @Override
    public void getVerificationcode(String phone, int type) {
        Map<String, String> params = new HashMap<>();
        params.put("mobile", phone);
        params.put("type", type+"");
        params.put("appToken", PreferenceUtil.getInstance(CustomApplication.getInstance()).getAppToken());
        params.put("sign","shanling");
        params.put("sessionId","0");
        Subscription subscribe= BuildFactory.getInstance().create(DeviceApi.class, HttpConstants.TRST_URL).getValidCode(params)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseResult<VerificationcodeBean>>() {
                    @Override
                    public void onCompleted() {

                    }
                    @Override
                    public void onError(Throwable e) {
                        String error = "";
                        try {
                                if (e instanceof ResultException) {
                                    String errorcode=((ResultException) e).getErrCode();
                                    error = CodeMessgeUtils.getMessage(errorcode);   //抛出异常，抓取数据，拿到失败的errormsg
                                } else {
//					error = "网络连接超时，请稍后再试...";
                                    error = CustomApplication.getInstance().getResources().getString(R.string.error1013);
                                }
                            if(mView==null){
                                return;
                            }
                            mView.getcodeFaild(error);
                            Log.e("error",  "=====Error=======>" + e.toString());
                            e.printStackTrace();
                        } finally {
                        }
                    }
                    @Override
                    public void onNext(BaseResult<VerificationcodeBean> result) {
                        if(mView==null){
                            return;
                        }
                        Log.e("weiyu","获取成功"+result.getData().getValidCode());
                        if(result.hasSuccess()){
                            mView.getcodeSuccess(result.getData().getValidCode());
                        }else {
                            mView.getcodeFaild(CodeMessgeUtils.getMessage(result.getErrCode()));
                        }
                    }
                });
        addSubscription(subscribe);
    }

    @Override
    public void registered(final String phone, final String userPwd, String validCode) {
        Map<String, String> params = new HashMap<>();
        params.put("userName", phone);
        params.put("userPwd", Md5Util.getMD5String(userPwd));
        params.put("validCode",validCode );
        params.put("reqAuth","shanling");
        params.put("appToken",PreferenceUtil.getInstance(CustomApplication.getInstance()).getAppToken() );
        params.put("sign","shanling");
        params.put("sessionId","0");
        Subscription subscribe= BuildFactory.getInstance().create(DeviceApi.class, HttpConstants.TRST_URL).doRegist(params)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseResult<String>>() {
                    @Override
                    public void onCompleted() {

                    }
                    @Override
                    public void onError(Throwable e) {
                        String error = "";
                        try {
                                if (e instanceof ResultException) {
                                    String errorcode=((ResultException) e).getErrCode();
                                    error = CodeMessgeUtils.getMessage(errorcode);   //抛出异常，抓取数据，拿到失败的errormsg
                                } else {
//					error = "网络连接超时，请稍后再试...";
                                    error = CustomApplication.getInstance().getResources().getString(R.string.error1013);
                                }
                            if(mView==null){
                                return;
                            }
                            mView.registeredFaild(error);
                            Log.e("error",  "=====Error=======>" + e.toString());
                            e.printStackTrace();
                        } finally {
                        }
                    }
                    @Override
                    public void onNext(BaseResult<String> result) {
                        if(mView==null){
                            return;
                        }
                             if(result.hasSuccess()){
                            mView.registeredSuccess(phone,userPwd);
                        }else {
                            mView.registeredFaild(CodeMessgeUtils.getMessage(result.getErrCode()));
                        }
                    }
                });
        addSubscription(subscribe);
    }

    @Override
    public void getToken() {
        Map<String, String> params = new HashMap<>();
        params.put("os","android");
        params.put("osVersion", PhoneUtils.getSystemVersion());
        params.put("phoneModel",PhoneUtils.getSystemModel());
        params.put("phoneDpi",PhoneUtils.getWindowWidth()+"*"+PhoneUtils.getWindowHeigh());
        params.put("appVersion", BuildConfig.VERSION_CODE+"");
        params.put("appChannel", "google");
        params.put("sign","shanling");
        params.put("appToken", "");
        params.put("sessionId","0");
        Subscription subscribe= BuildFactory.getInstance().create(DeviceApi.class, HttpConstants.TRST_URL).getToken(params)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseResult<ApptokenBean>>() {
                    @Override
                    public void onCompleted() {

                    }
                    @Override
                    public void onError(Throwable e) {
                        String error = "";
                        try {
                                if (e instanceof ResultException) {
                                    String errorcode=((ResultException) e).getErrCode();
                                    error = CodeMessgeUtils.getMessage(errorcode);   //抛出异常，抓取数据，拿到失败的errormsg
                                } else {
//					error = "网络连接超时，请稍后再试...";
                                    error = CustomApplication.getInstance().getResources().getString(R.string.error1013);
                                }
                            if(mView==null){
                                return;
                            }
                            mView.getTokenFaild(error);
                            Log.e("error",  "=====Error=======>" + e.toString());
                            e.printStackTrace();
                        } finally {
                        }
                    }
                    @Override
                    public void onNext(BaseResult<ApptokenBean> apptokenBeanBaseResult) {
                        if(mView==null){
                            return;
                        }
                        if(apptokenBeanBaseResult.hasSuccess()){
                            mView.getTokenSuccess(apptokenBeanBaseResult.getData().getAppToken());
                        }else {
                            mView.getTokenFaild(CodeMessgeUtils.getMessage(apptokenBeanBaseResult.getErrCode()));
                        }
                    }
                });

        addSubscription(subscribe);
    }
}
